<template>
  <el-dialog
    :modelValue="showDlg"
    title="分配权限"
    width="500px"
    :before-close="handleClose"
  >
    <div class="content">
      <el-tree
        ref="tree"
        :data="menuArr"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="selectArr"
        :props="defaultProps"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElButton } from 'element-plus'
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { reqAllMenuList, reqSetPermisstion } from '@/api/acl/role/role'
import type { RoleData, MenuResponseData, MenuList } from '@/api/acl/role/type'

let $emit = defineEmits('closeDlg', 'saveDlg')
import type { FormInstance, FormRules } from 'element-plus'
let props = defineProps({
  showDlg: {
    type: Boolean,
    default: false,
  },
  id: Number,
  roleName: String,
})
const formRef = ref<FormInstance>()
let RoleParams = reactive<RoleData>({
  roleName: '',
  id: 0,
})
let menuArr = ref<MenuList>([])
//获取tree组件实例
let tree = ref<any>()
let selectArr = ref<number[]>([])
const defaultProps = {
  children: 'children',
  label: 'name',
}

onMounted(async () => {
  RoleParams.roleName = props.roleName || ''
  RoleParams.id = props.id || 0
  Object.assign(RoleParams, RoleParams)
  //根据职位获取权限的数据
  let result: MenuResponseData = await reqAllMenuList(RoleParams.id as number)
  if (result.code == 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
})

const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })

  return initArr
}
const title = computed(() => {
  return props.id ? '修改' : '新增'
})

const handleClose = () => {
  $emit('closeDlg', false)
}
const saveForm = async () => {
  const roleId = RoleParams.id as number
  let arr = tree.value.getCheckedKeys()
  let arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  const res:any = await reqSetPermisstion(roleId, permissionId)
  if (res.code == 200) {
    ElMessage.success('分配权限成功')
  } else {
    ElMessage.warning('分配权限失败')
  }
  $emit('saveDlg', false)
}
</script>
<style lang="scss" scoped>
::v-deep .el-input,
.el-form-item {
  width: 100%;
}
.content {
  height: 500px;
  overflow: auto;
}
</style>
